package com.wangyadong.hobby.nio.charter1;


import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class EchoCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {
    private AsynchronousSocketChannel asynchronousServerSocketChannel;

    public EchoCompletionHandler(AsynchronousSocketChannel channel) {
        this.asynchronousServerSocketChannel = channel;
    }

    @Override
    public void completed(Integer result, ByteBuffer buffer) {
        buffer.flip();
        this.asynchronousServerSocketChannel.write(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(Integer result, ByteBuffer attachment) {
                if (attachment.hasRemaining()) {
                    asynchronousServerSocketChannel.write(buffer, buffer, this);
                } else {
                    attachment.compact();
                    asynchronousServerSocketChannel.read(buffer, buffer, EchoCompletionHandler.this);
                }
            }

            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {
                try {
                    asynchronousServerSocketChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        try {
            asynchronousServerSocketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
